/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.controllers.mobileweb;

import app.Const;
import app.interceptors.MobileWxMemberInterceptor;
import app.models.booking.KtvBooking;
import app.models.booking.KtvProject;
import app.models.member.Member;
import com.github.sog.controller.AjaxMessage;
import com.github.sog.controller.BasicController;
import com.github.sog.validator.ValidatorKit;
import com.jfinal.aop.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * <p>
 * .
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-05-25 15:33
 * @since JDK 1.6
 */
@Before(MobileWxMemberInterceptor.class)
public class KtvController extends BasicController {
    public static final Logger logger = LoggerFactory.getLogger(KtvController.class);

    /**
     * The index route.
     */
    public void index() {
        render("index.ftl");
    }

    public void list() {
        try {
            List<KtvProject> ktvProjects = KtvProject.dao.findByAll();
            renderJson(AjaxMessage.ok(ktvProjects));
        } catch (Exception e) {
            logger.error("ktv list select error !", e);
            renderJson(AjaxMessage.failure("error!"));
        }
    }

    public void item() {
        long id = getParaToLong("id", 0l);
        long mid = getParaToLong(Const.MEMBER_PARAM, 0l);
        final KtvProject record = KtvProject.dao.findByPk(id);
        setAttr("record", record);
        if (record != null) {
            setAttr("count", KtvBooking.dao.countByProject(record.getLong("id")));
        }
        render("item.ftl");
    }

    public void book() {
        long projectId = getParaToLong("projectId", 0l);
        long mid = getParaToLong(Const.MEMBER_PARAM, 0l);

        String name = getPara("name");
        String phone = getPara("phone");

        if (!ValidatorKit.isMobile(phone)) {
            renderJson(AjaxMessage.failure("手机输入不正确"));
            return;
        }

        final Member member = Member.dao.findById(mid);
        if (member == null) {
            renderJson(AjaxMessage.failure("您还不是会员，无法预订"));
            return;
        }
        final KtvProject ktvProject = KtvProject.dao.findById(projectId);
        if (ktvProject == null) {
            renderJson(AjaxMessage.failure("没有查询到预订项目"));
            return;
        }

        boolean booking = KtvBooking.dao.booking(ktvProject, name, phone, member);
        if (booking) renderSuccess();
        else renderFailure("预定KTV失败！");

    }

    public void ok() { }
}